package fina2.dcs.fis;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;
import fina2.dcs.system.SysStringPk;

@Stateful
@Name("regSession")
@Scope(ScopeType.SESSION)
@LocalBinding(jndiBinding = "RegionSession/local")
@AutoCreate
public class RegionSession implements RegionLocal,Serializable {
	@PersistenceContext
	private EntityManager em;
	
	@Logger
	private Log log;

	@EJB
	private SysStringLocal sysLocal;

	private List<Region> allRegions = new ArrayList<Region>();

	public void init() {
		log.info("Getting All Regions...");
		try {

			List<BigDecimal> ids = new ArrayList<BigDecimal>();
			ids = em.createQuery("SELECT DISTINCT r.regionStrId FROM " + Region.class.getName() + " r").getResultList();

			StringBuffer sb = new StringBuffer(ids.toString());
			sb.replace(0, 1, "");
			sb.replace(sb.toString().length() - 1, sb.toString().length(), "");

			List<SysString> regionDescs = sysLocal.getAllValues(sb.toString(), LanguageSession.langId);
			for (int i = 0; i < regionDescs.size(); i++) {

			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		log.info("Regions loaded...");
	}

	public void addRegion() {
		// TODO Auto-generated method stub

	}

	@Remove
	@Destroy
	public void remove() {
		// TODO Auto-generated method stub

	}

	public void removeRegion() {
		// TODO Auto-generated method stub

	}

	public void updateRegion() {
		// TODO Auto-generated method stub

	}

	public List<Region> getAllRegions() {
		return allRegions;
	}

	public void setAllRegions(List<Region> allRegions) {
		this.allRegions = allRegions;
	}

	public Region findById(BigDecimal id) {
		Region r = null;
		try {

			r = em.find(Region.class, id);
			if (r != null) {
				SysString sRegion = sysLocal.findByPk(new SysStringPk(r.getRegionStrId(), LanguageSession.langId));
				r.setRegionName((sRegion != null) ? sRegion.getValue() : null);
				SysString sCity = sysLocal.findByPk(new SysStringPk(r.getCityStrId(), LanguageSession.langId));
				r.setCityName((sCity != null) ? sCity.getValue() : null);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return r;
	}

}
